<template>
  <div class="container clearfix">
    <div class="filter">
      <h2 class="title">筛选查询</h2>
      <div class="section">
        <span class="tip">项目名称</span>
        <div class="content">
          <el-input v-model="search_form.project_name" placeholder="请输入内容" />
        </div>
      </div>
      <div v-if="cateHidden" class="section">
        <span class="tip">分类</span>
        <el-select v-model="search_form.class_selected" placeholder="请选择">
          <el-option
            v-for="item in class_arr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">成团人数</span>
        <div class="content">
          <el-input v-model="search_form.group_num" placeholder="请输入内容" />
        </div>
      </div>
      <div class="section">
        <span class="tip">上架状态</span>
        <el-select v-model="search_form.status" placeholder="请选择">
          <el-option
            v-for="item in status_arr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">是否推荐</span>
        <el-select v-model="search_form.isRecommend" placeholder="请选择">
          <el-option
            v-for="item in isRecommend_arr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">医院名称</span>
        <div class="content">
          <el-input v-model="search_form.hospital_name" placeholder="请输入内容" />
        </div>
      </div>
      <div class="section">
        <span class="tip">省份</span>
        <el-select v-model="search_form.province_id" placeholder="请选择">
          <el-option
            v-for="item in provinceData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="btn-bar">
        <el-button type="primary" siae="small" icon="el-icon-search" @click="search()">查询</el-button>
        <el-button type="primary" plain class="el-icon-refresh" @click="reset">重置</el-button>
      </div>
      <div style="float:right">
        <el-button type="primary" @click="add_project()">
          添加项目
          <i class="el-icon-upload" />
        </el-button>
      </div>
    </div>
    <div class="data-table">
      <div class="Batch-operation">
        <el-button type="primary" plain class="el-icon-refresh" @click="BatchOperation">批量操作</el-button>
      </div>
      <h4 style="margin:20px">已选择{{ multipleSelection.length }}个项目</h4>
      <el-table
        v-loading="table_loading"
        :data="tableData"
        border
        height="660"
        align="center"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column prop="id" align="center" label="项目编号" />
        <el-table-column prop="sort" align="center" label="排序" />
        <el-table-column align="center" label="项目图片">
          <template slot-scope="scope">
            <img :src="common.img_url+scope.row.groupMasterPicture" width="100%" alt />
          </template>
        </el-table-column>
        <el-table-column prop="groupProjectName" align="center" label="项目名称" />
        <el-table-column prop="provinceName" align="center" label="省份" />
        <el-table-column prop="hospitalName" align="center" label="医院名称" />
        <el-table-column v-if="cateHidden" prop="projectCategoryName" align="center" label="项目分类" />
        <el-table-column prop="payType" align="center" label="价格类型">
          <template slot-scope="scope">
            <span v-if="scope.row.payType==0">定金</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="price" align="center" label="原价" /> -->
        <el-table-column prop="groupPrice,priceName" align="center" label="价格">
          <template slot-scope="scope">
            <span>单独全款：{{ scope.row.price }}</span>
            <span>单独定金：{{ scope.row.subscription }}</span>
            <span>拼团全款：{{ scope.row.groupPrice }}</span>
            <span>拼团定金：{{ scope.row.groupSubscription }}</span>
<!--            <span>拼团全款：{{ scope.row.groupPrice }}</span>-->
<!--            <span>原价全款：{{ scope.row.price }}</span>-->
<!--            <span>拼团定金：{{ (scope.row.groupPrice-0 )*0.3}}</span>-->
<!--            <span>原价定金：{{ (scope.row.price-0)*0.3 }}</span>-->
          </template>
        </el-table-column>
        <el-table-column prop="views" align="center" label="点击量" />
        <el-table-column prop="projectSales" align="center" label="成交率">
          <template slot-scope="scope">
            <span
              v-if="scope.row.projectSales-0"
            >{{ Math.ceil((scope.row.userViews-0)/(scope.row.projectSales-0))}}</span>
            <span v-else>0</span>
          </template>
        </el-table-column>

        <el-table-column prop="subsidies" align="center" label="奖励">
          <template
            slot-scope="scope"
          >{{ scope.row.subsidies === '0.00'?'无' : scope.row.subsidies }}</template>
        </el-table-column>
        <el-table-column align="center" label="立减券">
          <template slot-scope="scope">{{ scope.row.coupons === 0 ? '无' : scope.row.coupons }}</template>
        </el-table-column>
        <el-table-column align="center" label="结算类型">
          <template slot-scope="scope">
          <span v-if="scope.row.hospitalPriceType == '0'">固定金额</span>
          <span v-if="scope.row.hospitalPriceType == '1'">比例</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="结算金额">
          <template slot-scope="scope">
          {{scope.row.hospitalPriceValue}}<span v-if="scope.row.hospitalPriceType == '1'">%</span>
          </template>
        </el-table-column>
        <el-table-column prop="startGroupCount" align="center" label="发起拼团数" />
        <el-table-column prop="finishGroupCount" align="center" label="成团数" />
        <el-table-column prop="verificationCount" align="center" label="累计核销数" />
        <el-table-column align="center" label="上架状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="change_status($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否推荐">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isRecommend"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="change_isRecommend($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否推送到服务商小程序">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.serverShow"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="change_serverShow($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="groupSize" align="center" label="成团人数" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-button type="success" size="small" @click="search_detail(scope.row)">查看</el-button>
            <el-button type="primary" size="small" @click="rewrite (scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="delete_item(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-controller">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data_total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="批量操作" :visible.sync="centerDialogVisible" width="50%" center>
      <el-form label-width="80px" label-positionposition="right" :model="form" ref="form">
        <el-row>
          <el-col :span="12">
            <el-radio v-model="form.checked" label="1">复制</el-radio>
          </el-col>

          <el-col :span="12">
            <el-radio v-model="form.checked" label="2">修改医院</el-radio>
          </el-col>
          <el-col :span="10" class="checkedTab">
            <el-form-item label="数量" v-show="form.checked=='1'">
              <el-input v-model="form.copyNum" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="checkedTab">
            <el-form-item label="选择医院" v-show="form.checked=='2'">
              <el-select
                v-model="form.hos_id"
                placeholder="请选择"
                filterable
                @change="change_hos"
              >
                <el-option
                  v-for="item in hos_arr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="save">立即提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { provinceList } from "@/api/province";
import {
  deleteProject,
  projectGroupStatus,
  projectList,
  updateProjectIsRecommend,
  updateProjectServerShow,
  updateProjectStatus,
  batchCopyGroupProjectList,
  batchUpdateProjectHospital,
} from "@/api/project";
import { getCateDownList } from "@/api/category";
import { appType } from "@/utils/constanst";
import { getHospitalList } from "@/api/hospitalManage";
export default {
  name: "Projects",
  data() {
    return {
      centerDialogVisible: false, //批量弹窗显示控制
      form: { checked: null, copyNum: null, updateValue: null },
      multipleSelection: [], //列表复选框勾选数据
      projectIdList: [], //列表复选框勾选id
      hos_arr: [], //医院列表数据
      hos_id: "", //医院id
      hos_name: "", //   医院名称
      cateHidden: false, // 是否显示  默认不显示
      value: true,
      table_loading: false,
      class_arr: [],
      status_arr: [
        {
          value: "1",
          label: "已上架",
        },
        {
          value: "0",
          label: "未上架",
        },
      ],
      isRecommend_arr: [
        {
          value: "1",
          label: "已推荐",
        },
        {
          value: "0",
          label: "未推荐",
        },
      ],
      page_total: 1,
      data_total: 0,
      tableData: [],
      provinceData: [],
      page: 1,
      pageSize: 10,
      search_form: {
        //   项目名称
        project_name: "",
        //   成团人数
        group_num: "",
        //   分类
        class_selected: "",
        //   医院名称
        hospital_name: "",
        //   上架状态
        status: "",
        //   省份
        province_id: "",
        // 是否推荐
        isRecommend: "",
      },
      model: 0, // 0 初次加载   1表示条件筛选
    };
  },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.search_form);
    sessionStorage.setItem(keyname, value);
    next();
  },
  mounted() {
    if (sessionStorage.getItem(this.$route.name)) {
      this.search_form = JSON.parse(sessionStorage.getItem(this.$route.name));
    }
    this.search();
    if (appType === 4) {
      this.cateHidden = true;
    }
    this.get_catelist();
    this.get_province();
  },

  methods: {
    // 复选框勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;

      // console.log(val);
      if (val.length >= 1) {
        const arr1 = [];
        this.multipleSelection.forEach((item) => {
          arr1.push(item.id);
        });
        console.log(arr1);
        this.projectIdList = arr1;
      }
    },
    // 复选框禁用控制
    selectable(row, index) {
      // if (row.status == 1) {
      return true;
      // } else {
      // return false
      // }
    },
    //批量弹窗
    BatchOperation() {
      this.form.copyNum = null;
      this.form.checked = null;
      if (this.multipleSelection.length < 1) {
        return this.$message.warning("请先勾选批量操作的数据");
      }
      this.get_hoslist();

      this.centerDialogVisible = true;
    },
    //批量提交
    save() {
      if(this.form.checked == null ){
        this.$message.warning("请选择要操作的选项");
        return;
      }
       else if (this.form.checked == "2" && !(this.form.hos_id-0)) {
        this.$message.warning("请选择医院");
        return;
      } else if (this.form.checked == "1" && (this.form.copyNum-0) == 0) {
        this.$message.warning("请选择数量");
        return;
      }
      let data1 = {
        projectIdList: this.projectIdList,
        copyNum: this.form.copyNum - 0,
      };
      let data2 = {
        projectIdList: this.projectIdList,
        updateType: 1,
        updateValue: this.hos_id + "",
      };
      console.log(this.form.checked);
      this.btnFlag = true;//初始点击后禁用提交按钮
      if (this.form.checked == 1) {
        batchCopyGroupProjectList(data1).then((res) => {
          console.log("res", res);
          if (res.data.code == 0) {
            this.$message.success(res.data.msg);
            this.centerDialogVisible = false;
            this.search();
          } else {
            this.btnFlag = false;//异常时释放提交按钮
            this.$message.error(res.data.msg);
          }
        });
      } else {
        batchUpdateProjectHospital(data2).then((resquest) => {
          console.log("resquest", resquest);
          if (resquest.data.code == 0) {
            this.$message.success(resquest.data.msg);
            this.centerDialogVisible = false;
            this.search();
          } else {
            this.btnFlag = false;//异常时释放提交按钮
            this.$message.error(resquest.data.msg);
          }
        });
      }
    },
    // 获取医院列表
    get_hoslist() {
      getHospitalList({
        pageNum: 1,
        pageSize: 1000,
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            const arr = [];
            if (res.data.list) {
              res.data.list.forEach((item) => {
                arr.push({
                  value: item.id,
                  label: item.hospitalName,
                });
              });
              this.hos_arr = arr;
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 选择医院
    change_hos(res) {
      this.hos_arr.forEach((i) => {
        if (i.value === res) {
          this.hos_name = i.label;
          this.hos_id = i.value;
          console.log(this.hos_name);
          console.log(this.hos_id);
        }
      });
    },
    // 筛选
    search() {
      this.model = 1;
      this.get_list({
        pageNum: this.page,
        pageSize: this.pageSize,
        // id: 0,
        groupProjectName: this.search_form.project_name,
        projectCategoryId: this.search_form.class_selected + "",
        groupSize: this.search_form.group_num,
        status: this.search_form.status,
        isRecommend: this.search_form.isRecommend,
        provinceId:
          this.search_form.province_id === 0
            ? 999 + ""
            : this.search_form.province_id + "", // 如果筛选条件为全国时，传省份id为999
        hospitalName: this.search_form.hospital_name,
        keywordId:null,
        projectIds:""
      });
    },
    // 重置
    reset() {
      this.search_form.project_name = "";
      this.search_form.group_num = "";
      this.search_form.status = "";
      this.search_form.isRecommend = "";
      this.search_form.province_id = "";
      this.search_form.hospital_name = "";
      this.search_form.class_selected = "";
      this.get_list({
        pageNum: this.page,
        pageSize: this.pageSize,
        // id: 0,
        groupProjectName: "",
        projectCategoryId: "",
        groupSize: "",
        status: "",
        isRecommend: "",
        provinceId: "",
        hospitalName: "",
        keywordId:"",
        projectIds:""
      });
    },
    // 获取列表
    get_list(
      options = {
        pageNum: this.page,
        pageSize: this.pageSize,
        // id: 0,
        groupProjectName: this.search_form.project_name,
        projectCategoryId: this.search_form.class_selected + "",
        groupSize: this.search_form.group_num,
        status: this.search_form.status,
        isRecommend: this.search_form.isRecommend,
        provinceId:
          this.search_form.province_id === 0
            ? 999 + ""
            : this.search_form.province_id + "", // 如果筛选条件为全国时，传省份id为999
        hospitalName: this.search_form.hospital_name,
      }
    ) {
      if (this.model === 0) {
        options = {
          pageNum: this.page,
          pageSize: this.pageSize,
        };
      }
      this.table_loading = true;
      projectList(options)
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            res.data.list.forEach((item) => {
              item.status = item.status - 0;
            });
            this.tableData = res.data.list;
            this.data_total = res.data.count;
            this.page_total = Math.ceil(res.data.count / this.pageSize);
            this.table_loading = false;
          }
        })
        .catch((err) => {
          this.table_loading = false;
          //   this.$message.error('服务器网络错误，请稍后重试');
          this.$message.error(err);
        });
    },
    //添加项目
    add_project() {
      this.$router.push({
        path: "/add_projects",
        query: {
          page_status: 1,
        },
      });
    },
    // 查看详情
    search_detail(row) {
      this.$router.push({
        path: "/add_projects",
        // path: "/project_detail",
        query: { id: row.id,page_status: 3  },
      });
    },
    // 编辑项目
    rewrite(row) {
      this.$router.push({
        path: "/add_projects",
        query: { id: row.id, page_status: 2 },
      });
    },
    // 删除项目
    delete_item(row) {
      this.$confirm("确认删除该项目？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteProject({
            id: row.id - 0,
          })
            .then((result) => {
              const res = result.data;
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.search();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              this.$message.error("服务器网络错误，请稍后重试");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 上架状态修改-状态判断与执行
    change_status(status, item) {
      if (status === 0) {
        // 查询项目拼团状态-执行上架时
        projectGroupStatus({
          id: item.id,
          status: status + "",
        })
          .then((result) => {
            const groupStatus = result.data.data.groupStatus;
            if (groupStatus === 1) {
              // 无进行拼团
              this.change_project_status(status, item);
            } else {
              // 有正在进行的拼团
              this.$confirm("确认下架该项目？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.change_project_status(status, item);
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消下架",
                  });
                });
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else {
        this.change_project_status(status, item);
      }
    },
    // 上架状态修改
    change_project_status(status, item) {
      updateProjectStatus({
        id: item.id,
        status: status + "",
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            this.$message({
              message: "上架状态修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.msg);
          }
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 推荐状态修改
    change_isRecommend(isRecommend, item) {
      updateProjectIsRecommend({
        id: item.id,
        isRecommend: isRecommend,
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            this.$message({
              message: "推荐状态修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.msg);
          }
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 推送到服务商小程序状态修改
    change_serverShow(serverShow, item) {
      updateProjectServerShow({
        id: item.id,
        status: serverShow + "",
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            this.$message({
              message: "推送到服务商小程序状态修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.msg);
          }
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //获取省份
    get_province() {
      provinceList({})
        .then((res) => {
          this.provinceData = res.data.data.list;
        })
        .catch((res) => {
          this.$message.error("网络连接错误，请稍后再试");
        });
    },
    // 获取分类列表
    get_catelist() {
      getCateDownList({
        pageNum: 1,
        pageSize: 1000,
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 0) {
            const arr = [];
            res.data.list.forEach((item) => {
              arr.push({
                value: item.id,
                label: item.categoryName,
              });
            });
            this.class_arr = arr;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    //页码改变
    handleCurrentChange(page) {
      this.page = page;
      this.search();
    },
    //条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      this.search();
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  .filter {
    margin: 20px;
    background-color: #fff;
    box-shadow: 1px 1px 30px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    padding: 20px;
    position: relative;
    .title {
      font-size: 16px;
    }
    .section {
      display: inline-block;
      vertical-align: middle;
      margin-right: 20px;
      margin-top: 20px;
      .tip {
        font-size: 14px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 5px;
      }
      .content {
        display: inline-block;
        vertical-align: middle;
      }
      .inp {
        display: inline-block;
        vertical-align: middle;
        border: none;
        outline: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 6px;
      }
    }
    .btn-bar {
      position: absolute;
      right: 20px;
      top: 16px;
    }
  }
  .data-table {
    margin: 20px;
    background-color: #fff;
    box-sizing: border-box;
  }
  .page-controller {
    float: right;
    margin-right: 20px;
  }
  .Batch-operation {
    margin: 20px;
  }
  .checkedTab{
    margin-top: 30px;
  }
}
</style>

